<script setup>
import { useRouter } from 'vue-router';
import { ref } from 'vue';
import { addPostFn } from '@/api/post';
import { usePostListStore } from '@/stores/post';
import { useUserStore } from '@/stores/user';

const post = usePostListStore()
const user = useUserStore()
const router = useRouter()
const text = ref('')
const fileList = ref([])
const topics = ref([])
const show = ref(false)

function tofind() {
    router.push('/find')
}

function showTopic() {
    show.value = true
}

function addTopic(topic) {
    let flag = true
    topics.value.forEach(item => {
        if (item == topic) {
            flag = false
        }
    })
    if (flag) {
        topics.value.push(topic)

    }
    show.value = false
}

function deltopic(index) {
    // console.log(index);
    topics.value.splice(index, 1)
}

function toPost() {
    // console.log(fileList.value[0].content);
    addPostFn({
        postText: text.value,
        userid: user.userInfo.userid,
        topics: topics.value,
        img: fileList.value[0].content,
    }).then(res =>{
        // console.log(res);
        router.push('/find')
    })
}

</script>

<template>
    <div class="main">
        <van-nav-bar title="发布" left-text="返回" left-arrow @click-left="tofind" />
        <div class="content">
            <van-cell-group inset>
                <van-field style="font-size: 20px;" v-model="text" placeholder="一起聊聊吧" />
            </van-cell-group>
            <van-uploader v-model="fileList" max-count='1' />
            <br>
            <div class="topic" style="background-color: #d5d5d5;" v-for="(item, index) in topics">
                # {{ item }}
                <van-icon name="close" size="12px" @click="deltopic(index)"></van-icon>
            </div>
            <div class="topic" @click="showTopic"># 添加话题</div>
            <van-popup v-model:show="show" class="pop">
                <van-cell v-for="item in post.topicList" :title="item" @click="addTopic(item)"></van-cell>
            </van-popup>
        </div>
        <van-button @click="toPost" class="button">发布</van-button>
    </div>
</template>
<style lang="scss" scoped>
.button {
    background-color: aqua;
    margin: 0 20px;
    font-size: 20px;
    font-weight: bold;
}

.topic {
    padding: 10px;
    background-color: #e5e5e5;
    display: inline-block;
    border-radius: 50px;
    margin: 10px;
}

.pop {
    width: 150px;
}
</style>